from urllib.parse import parse_qs

from html_00_common_header import generate_common_header
from html_01_common_footer import generate_common_footer


def handle_practice_path(self, parsed_path):
    query_params = parse_qs(parsed_path.query)

    question_type = query_params.get('type', [None])[0]
    start_str = query_params.get('start', [None])[0]
    end_str = query_params.get('end', [None])[0]

    if not question_type or not start_str or not end_str:
        self.send_error(400, '', '缺少必要的参数')
        return

    try:
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write((generate_common_header("练习题目", "3") +
                          generate_body(self, question_type, start_str, end_str) +
                          generate_common_footer()).encode('utf-8'))
    except ValueError as e:
        self.send_error(400, '', str(e))


def generate_body(self, question_type, start_str, end_str):
    start = int(start_str)
    end = int(end_str)
    expected_count = end - start + 1
    practice_questions = [q for q in self.questions if
                          q['题目类型'] == question_type and start <= q['题号'] <= end]
    actual_count = len(practice_questions)
    # 收集已有的题号
    existing_numbers = [q['题号'] for q in practice_questions]
    # 找出缺少的题号
    missing_numbers = [num for num in range(start, end + 1) if num not in existing_numbers]

    body = ""
    if actual_count != expected_count:
        body += f'<div style="color: red; font-size: 1.5em; font-weight: bold;">注意：预期筛选出 {expected_count} 道题目，但实际只筛选出 {actual_count} 道，缺少题号 {", ".join(map(str, missing_numbers))}，请检查并修正题库。</div>'
    # 按顺序输出题目和缺少的题号
    for num in range(start, end + 1):
        if num in existing_numbers:
            q = next(q for q in practice_questions if q['题号'] == num)
            body += f'<a href="/question/{self.questions.index(q)}">{q["题号"]}. {q["问题"][:30]}...</a><br>'
        else:
            body += f'<div style="color: red; font-weight: bold;">缺少题号 {num}，请检查题库。</div><br>'
    return body
